const Vocabulary = require('../../database/models/vocabulary');

class LearningProgressService {
  constructor(db) {
    this.vocabularyModel = new Vocabulary(db);
  }

  /**
   * Get vocabulary learning statistics
   * @returns {Promise} - Promise that resolves with learning statistics
   */
  async getLearningStatistics() {
    try {
      // Get total word count
      const totalResult = await this.vocabularyModel.db.get('SELECT COUNT(*) as total FROM vocabulary');

      // Get known word count
      const knownResult = await this.vocabularyModel.db.get(
        "SELECT COUNT(*) as known FROM vocabulary WHERE ok = 'YES'"
      );

      // Get IELTS word count
      const ieltsResult = await this.vocabularyModel.db.get(
        "SELECT COUNT(*) as ielts FROM vocabulary WHERE ielst = 'YES'"
      );

      // Get known IELTS word count
      const knownIeltsResult = await this.vocabularyModel.db.get(
        "SELECT COUNT(*) as known_ielts FROM vocabulary WHERE ok = 'YES' AND ielst = 'YES'"
      );

      return {
        total: totalResult.total || 0,
        known: knownResult.known || 0,
        ielts: ieltsResult.ielts || 0,
        knownIelts: knownIeltsResult.known_ielts || 0,
        unknown: (totalResult.total || 0) - (knownResult.known || 0),
        unknownIelts: (ieltsResult.ielts || 0) - (knownIeltsResult.known_ielts || 0),
      };
    } catch (err) {
      throw new Error(`Failed to get learning statistics: ${err.message}`);
    }
  }

  /**
   * Get word learning history
   * @param {number} limit - Number of records to return
   * @returns {Promise} - Promise that resolves with learning history
   */
  async getLearningHistory(limit = 30) {
    try {
      const history = await this.vocabularyModel.db.all(
        'SELECT word, ok, ielst, updated_at FROM vocabulary WHERE ok = ? OR ielst = ? ORDER BY updated_at DESC LIMIT ?',
        ['YES', 'YES', limit]
      );

      return history;
    } catch (err) {
      throw new Error(`Failed to get learning history: ${err.message}`);
    }
  }
}

module.exports = LearningProgressService;
